<div id="nodeDataSection" class="content-section container-fluid py-4">
    <div class="bg-white rounded-lg shadow-lg p-6">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h3 class="text-xl font-bold">节点数据查询</h3>
            <div class="d-flex gap-2">
                <select id="nodeTypeSelect" class="form-select" style="width: 200px;" onchange="loadNodeData()">
                    <option value="">请选择节点类型</option>
                    <option value="Artifact">文物基因</option>
                    <option value="Caizhi">材质基因</option>
                    <option value="CulturalItem">文物</option>
                    <option value="Image1">图片</option>
                    <option value="InstrumentGene">器型基因</option>
                </select>
                <button onclick="showCreateModal()" class="btn btn-primary">
                    <i class="fas fa-plus"></i> 新增节点
                </button>
            </div>
        </div>
        
        <!-- 图表展示区域 -->
        <div id="chartContainer" class="mb-4" style="height: 400px;"></div>
        
        <!-- 表格展示区域 -->
        <div class="table-responsive">
            <table id="nodeDataTable" class="table table-hover table-bordered">
                <thead>
                    <tr id="tableHeader" class="bg-light"></tr>
                </thead>
                <tbody id="tableBody"></tbody>
            </table>
        </div>

        <!-- 新增节点模态框 -->
        <div class="modal fade" id="nodeModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="modalTitle">新增节点</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form id="nodeForm">
                            <div id="formFields"></div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="saveNode()">保存</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 确认删除模态框 -->
        <div class="modal fade" id="deleteModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">确认删除</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        确定要删除这个节点吗？此操作不可撤销。
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-danger" onclick="confirmDelete()">删除</button>
                    </div>
                </div>
            </div>
        </div>

        <style>
            /* 表格样式优化 */
            .table {
                width: 100%;
                margin-bottom: 1rem;
                background-color: transparent;
            }

            /* 表格单元格样式 */
            .table td, .table th {
                padding: 0.75rem;
                vertical-align: middle;
                max-width: 250px; /* 限制单元格最大宽度 */
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }

            /* 鼠标悬停显示完整内容 */
            .table td:hover {
                white-space: normal;
                overflow: visible;
                position: relative;
                z-index: 1;
                background-color: #f8f9fa;
            }

            /* 表头样式 */
            .table thead th {
                background-color: #f8f9fa;
                border-bottom: 2px solid #dee2e6;
                font-weight: 600;
                color: #495057;
            }

            /* 斑马纹样式 */
            .table tbody tr:nth-of-type(odd) {
                background-color: rgba(0, 0, 0, 0.02);
            }

            /* 响应式容器样式 */
            .table-responsive {
                overflow-x: auto;
                -webkit-overflow-scrolling: touch;
                max-height: 500px; /* 限制表格最大高度 */
                overflow-y: auto;
            }

            /* 表格边框样式 */
            .table-bordered {
                border: 1px solid #dee2e6;
            }

            /* 鼠标悬停行样式 */
            .table-hover tbody tr:hover {
                background-color: rgba(0, 0, 0, 0.075);
            }
        </style>
            
            <!-- 分页控件 -->
            <div class="d-flex justify-content-between align-items-center mt-4">
                <div class="d-flex align-items-center">
                    <span class="me-2">每页显示:</span>
                    <select id="pageSizeSelect" class="form-select form-select-sm" style="width: 80px;" onchange="changePageSize()">
                        <option value="10">10</option>
                        <option value="20">20</option>
                        <option value="50">50</option>
                    </select>
                </div>
                <nav aria-label="数据分页">
                    <ul class="pagination mb-0" id="pagination"></ul>
                </nav>
            </div>
        </div>
    </div>
</div>

<!-- 添加必要的 JavaScript -->
<script>
let currentNodeType = '';
let editingNodeId = null;

// 修改 showCreateModal 函数
function showCreateModal() {
    editingNodeId = null;
    const nodeType = document.getElementById('nodeTypeSelect').value;
    if (!nodeType) {
        alert('请先选择节点类型');
        return;
    }
    
    document.getElementById('modalTitle').textContent = '新增数据';
    const formFields = document.getElementById('formFields');
    formFields.innerHTML = '';
    
    // 生成随机ID
    const randomId = generateRandomId(nodeType);
    
    // 添加隐藏的ID字段
    formFields.innerHTML = `
        <div class="mb-3">
            <label class="form-label">ID (自动生成)</label>
            <input type="text" class="form-control" name="id" value="${randomId}" readonly>
        </div>
    `;
    
    // 添加其他字段
    const fields = NODE_TYPES[nodeType].display_fields.filter(field => field !== 'id');
    fields.forEach(field => {
        formFields.innerHTML += `
            <div class="mb-3">
                <label class="form-label">${field}</label>
                <input type="text" class="form-control" name="${field}" required>
            </div>
        `;
    });
    
    const modal = new bootstrap.Modal(document.getElementById('nodeModal'));
    modal.show();
}

// 添加生成随机ID的函数
function generateRandomId(nodeType) {
    const prefix = nodeType === 'CulturalItem' ? 'A' : 
                  nodeType === 'Artifact' ? 'B' :
                  nodeType === 'Caizhi' ? 'C' :
                  nodeType === 'Image1' ? 'I' :
                  nodeType === 'InstrumentGene' ? 'G' : 'X';
                  
    const randomNum = Math.floor(Math.random() * 9999).toString().padStart(4, '0');
    return `${prefix}${randomNum}`;
}

// 修改 saveNode 函数中的验证部分
async function saveNode() {
    const nodeType = document.getElementById('nodeTypeSelect').value;
    const form = document.getElementById('nodeForm');
    
    // 验证必填字段
    const requiredFields = ['id', ...NODE_TYPES[nodeType].display_fields];
    const missingFields = [];
    requiredFields.forEach(field => {
        if (!form.elements[field].value) {
            missingFields.push(field);
        }
    });
    
    if (missingFields.length > 0) {
        alert(`请填写以下必要字段：${missingFields.join(', ')}`);
        return;
    }
    
    const formData = new FormData(form);
    const data = Object.fromEntries(formData);
    
    try {
        const response = await fetch(`/api/nodes/${nodeType}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        if (result.success) {
            bootstrap.Modal.getInstance(document.getElementById('nodeModal')).hide();
            await loadNodeData();
            alert('数据添加成功');
        } else {
            alert(result.message || '添加失败');
        }
    } catch (error) {
        console.error('Error saving data:', error);
        alert('保存失败，请重试');
    }
}

// 修改 confirmDelete 函数
async function confirmDelete() {
    if (!editingNodeId) return;
    
    const nodeType = document.getElementById('nodeTypeSelect').value;
    try {
        const response = await fetch(`/api/nodes/${nodeType}/${editingNodeId}`, {
            method: 'DELETE'
        });
        
        const result = await response.json();
        if (result.success) {
            bootstrap.Modal.getInstance(document.getElementById('deleteModal')).hide();
            await loadNodeData(); // 重新加载数据
            alert('删除成功');
        } else {
            alert(result.message || '删除失败');
        }
    } catch (error) {
        console.error('Error deleting node:', error);
        alert('删除失败，请重试');
    }
}

function renderTable(page) {
    currentPage = page;
    const start = (page - 1) * pageSize;
    const end = start + pageSize;
    const pageData = currentData.slice(start, end);

    // 渲染表头
    const tableHeader = document.getElementById('tableHeader');
    if (currentData.length > 0) {
        const headers = Object.keys(currentData[0].properties);
        tableHeader.innerHTML = headers.map(header => 
            `<th class="px-4 py-2 bg-gray-100">${header}</th>`
        ).join('') + '<th class="px-4 py-2 bg-gray-100">操作</th>';  // 添加操作列
    }

    // 渲染表体
    const tbody = document.getElementById('tableBody');
    tbody.innerHTML = pageData.map(item => `
        <tr class="hover:bg-gray-50">
            ${Object.entries(item.properties).map(([key, value]) => 
                `<td class="px-4 py-2 border-b" title="${value || '-'}">${value || '-'}</td>`
            ).join('')}
            <td class="px-4 py-2 border-b text-center">
                <button onclick='showEditModal(${item.identity}, ${JSON.stringify(item.properties)})' 
                    class="btn btn-sm btn-primary me-2">
                    编辑
                </button>
                <button onclick='showDeleteModal(${item.identity})' 
                    class="btn btn-sm btn-danger">
                    删除
                </button>
            </td>
        </tr>
    `).join('');

    renderPagination();
}
</script>